<script setup>
import {host_custom} from "@/host.js";
import axios from "axios";
import {onBeforeUnmount, ref} from "vue";
const searchThings = ref('')
const searchResult = ref([])
let searchDelay
const closeBtn = ref()
async function searchHandle() {
  clearTimeout(searchDelay)
  searchDelay = setTimeout(async ()=>{
    const res = await axios.get(host_custom + '/searchThings', {params: {searchThings: searchThings.value}})
    searchResult.value = res.data
  },800)
}

onBeforeUnmount(()=> {
  closeBtn.value.click()
})
</script>

<template>
  <div class="modal fade" id="searchModal" tabindex="-1" aria-labelledby="searchModal" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5" id="exampleModalLabel"> 搜索好友</h1>
          <button type="button" ref="closeBtn" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form>
            <div class="mb-3">
              <input type="text" placeholder="用户名" @input="searchHandle" v-model.trim="searchThings"  class="form-control" id="recipient-name">
            </div>
          </form>

          <div class="resultFrame">
            <div class="my-2 small" v-show="searchResult.length>0">找到{{searchResult.length}}条结果</div>
            <template v-for="val of searchResult">
              <router-link :to="`/checkUserProfile/${val.id}`" class="text-decoration-none">
                <div class="searchResult d-flex align-items-center justify-content-between p-2">
                  <div>
                    <img class="rounded-circle" :src="host_custom+'/pfp/'+val.pfp" width="35px" height="35px" :alt="val.name">
                    <span class="px-2">{{val.name}}</span>
                  </div>

                  <span>用户</span>
                </div>
              </router-link>
            </template>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="submit" class="btn btn-primary" @click="searchHandle">搜索</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.searchResult{
  transition: none;
}
.searchResult:hover {
  border-radius: 8px;
  background-color: rgba(129, 129, 129, 0.15);
}
</style>